<#include "../../components/cc-upload.ftl"/>
<#include "../../components/mixin-fixHeight.ftl"/>
<script type="text/x-template" id="batch-file-upload-dialog">
    <div>
    <custom-dialog class="batch-file-upload-dialog" :options="dialogOptions"
                   :closefn="close">
        <div slot="dialogContent">
            <div class="batch-file-upload-dialog__actions">
                <el-button type="primary" @click="handleSubmit">
                    保存
                </el-button>
                <el-button @click="handleCancel">
                    关闭
                </el-button>
            </div>
            <el-form ref="form" label-width="120px" :model="this">
                <div>
                    JMX文件：
                </div>
                <cc-upload :multiple="true" class="batch-file-upload-dialog__uploader" ref="upload"
                           @upload="handleUpload">
                    <template slot="preview" scope="{fileList: fileList}">
                        <div class="upload-file-list__item-wrapper" v-for="(file, index) in fileInfoList" :key="index">
                            <div class="upload-file-list__item">
                                <div class="upload-file-list__error" v-if="file.upload.status === 'error'">
                                    上传失败: {{ file.upload.message }}
                                </div>
                                <div v-if="file.upload.status === 'uploading'" class="upload-file-list__item-wrapper">
                                    <el-progress :width="180" type="circle"
                                                 :percentage="file.upload.percentage"></el-progress>
                                </div>
                            </div>
                            <div class="file-info">
                                <el-form-item :prop="'fileInfoList.' + index + '.originName'" :rules="rules.originName"
                                              label="文件原始名称">
                                    <el-input v-model="file.originName"/>
                                </el-form-item>
                                <el-form-item label="文件新名称">
                                    {{ file.newFileName }}
                                </el-form-item>
                                <el-form-item :prop="'fileInfoList.' + index + '.projectType'" :rules="rules.projectType" label="所属项目">
                                    <el-select v-model="fileInfoList[index].projectType">
                                        <el-option
                                                v-for="(item, index) in projectTypeOptions"
                                                :key="index"
                                                :value="item.value"
                                                :label="item.label"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </div>
                            <i
                                    v-if="file.status !== 'uploading'"
                                    class="upload-file-list__remove el-icon el-icon-close"
                                    title="移除"
                                    @click="handleRemoveFile(file, index)"
                            />
                        </div>
                        <el-button :disabled="mode === 'edit' && fileInfoList.length >=1" type="primary"
                                   class="upload-file-list__add" @click="$refs.upload.handleSelectFile()">
                            点击选择文件
                        </el-button>
                        <el-button @click="showProjectTypeSelector = true">
                            批量设置所属项目
                        </el-button>
                    </template>
                </cc-upload>
            </el-form>
        </div>
    </custom-dialog>
        <el-dialog
                class="project-type-selector"
                title="选择所属项目"
                size="tiny"
                :visible.sync="showProjectTypeSelector">
            <el-tag v-for="(item, index) in projectTypeOptions" :key="index" @click.native="handleBatchSetProjectType(item)">
                {{ item.label }}
            </el-tag>
        </el-dialog>
    </div>
</script>

<script>
    Vue.component('batch-file-upload-dialog', {
        template: '#batch-file-upload-dialog',
        mixins: [window.ccMixIn.fixHeight],
        data() {
            return {
                urls: {
                    uploadJmxFile: '/testCase/uploadJmxFile',
                    save: '/testCase/save'
                },
                dialogOptions: {
                    title: '上传jmx文件',
                    visible: true,
                    size: 'full'
                },
                mode: 'create',
                showProjectTypeSelector:false,
                projectTypeOptions:[],
                fileInfoList: [],
                rules: {
                    originFileName: [
                        {required: true, message: '请填写文件原始名称'}
                    ],
                    projectType: [
                        {required: true, message: '请选择所属项目'}
                    ]
                }
            }
        },
        methods: {
            close: function () {
                this.$emit("close");
            },
            handleBatchSetProjectType(type) {
                this.fileInfoList.forEach(function(item) {
                    item.projectType = type.value
                })
                this.showProjectTypeSelector = false
            },
            handleUpload(file, fileItem) {
                const fileInfo = {
                    upload: fileItem,
                    originName: undefined,
                    projectType: undefined,
                    newFileName: undefined,
                    jmxConfigJson: undefined

                }
                this.fileInfoList.push(fileInfo)
                fileItem.status = 'uploading'
                const formData = new FormData()
                formData.append('file', file)
                $.ajax({
                    method: 'post',
                    processData: false,
                    contentType: false,
                    dataType: 'json',
                    url: this.urls.uploadJmxFile,
                    data: formData,
                    xhr: function () {
                        var xhr = new window.XMLHttpRequest();
                        xhr.upload.addEventListener("progress", function (evt) {
                            if (evt.lengthComputable) {
                                fileItem.percentage = evt.loaded / evt.total

                            }
                        }, false);
                        return xhr;
                    },
                    success: function (result) {
                        if (result.code == 0) {
                            const uploadResult = result.data[0]
                            fileInfo.originName = uploadResult.originFileName
                            fileInfo.newFileName = uploadResult.newFileName
                            fileInfo.jmxConfigJson = uploadResult.jmxConfigJson
                            fileItem.status = 'success'
                        } else {
                            fileItem.status = 'error'
                            fileItem.message = result.msg
                        }
                    }.bind(this),
                    error: function (error) {
                        fileItem.status = 'error'
                        fileItem.message = '网络错误'
                    }.bind(this)
                });
            },
            handleRemoveFile(file, index) {
                this.$refs.upload.handleRemove(file.upload)
                this.fileInfoList = this.fileInfoList.filter(function (item, i) {
                    return i !== index
                })
            },
            getFormData() {
                const id = this.id
                const fileJsonData = this.fileInfoList.map(function (item) {
                    return {
                        id: id,
                        originName: item.originName,
                        testCaseFilePath: item.newFileName,
                        jmxConfigJson: item.jmxConfigJson,
                        projectType: item.projectType
                    }
                })
                const data = {jsonStr: JSON.stringify(fileJsonData)}
                return data
            },
            setFormData(data) {
                data = JSON.parse(JSON.stringify(data))
                data.upload = {
                    status: 'success',
                    dataUrl: data.url
                }
                this.id = data.id
                this.fileInfoList.push(data)
            },
            validateFormData(cb) {
                this.$refs.form.validate(function (valid) {
                    if (valid) {
                        if (this.fileInfoList.length === 0) {
                            this.$message({
                                type: 'error',
                                message: '最少要创建一个文件，才能保存'
                            })
                            cb(true)
                        } else {
                            cb()
                        }
                    } else {
                        this.$message({
                            type: 'error',
                            message: '请把表单填写完整'
                        })
                        cb(true)
                    }
                }.bind(this))
            },
            handleSubmit() {
                this.validateFormData(function (err) {
                    if (!err) {
                        const data = this.getFormData()
                        this.ajax(this.urls.save, data, function (result) {
                            if (result.success) {
                                this.$message({
                                    showClose: true,
                                    message: '保存成功',
                                    type: 'success'
                                })
                                this.$emit("close");
                            } else {
                                this.$message(result.msg);
                            }
                        }.bind(this));
                    }
                }.bind(this))
            },
            handleCancel() {
                this.$emit("close");
            },
            loadProjectTypeOptions(){
                this.ajax('/v1/dict/getTypes/projectType', {
                }, function (data) {
                    if (data.code === '0') {
                        this.projectTypeOptions=data.data;
                    } else {
                        this.$message(data.msg);
                    }
                }.bind(this));
            },
            init() {
              this.loadProjectTypeOptions();
            }
        },
        created() {
            this.FastDevTool = new window.FastDevTool()
            if (window.mode) {
                this.mode = window.mode
            }
            if (window.initData) {
                this.setFormData(window.initData)
            }
            this.init()
        }
    })
</script>
<style>
    .batch-file-upload-dialog {
    }

    .batch-file-upload-dialog__actions {
        padding: 15px;
        border-bottom: 1px solid #ccc;
        margin-bottom: 20px;
    }

    .batch-file-upload-dialog .upload-file-list__item,
    .batch-file-upload-dialog .file-info {
        display: inline-block;
        vertical-align: top;
    }

    .batch-file-upload-dialog__label,
    .batch-file-upload-dialog__uploader {
        display: inline-block;
        vertical-align: top;
    }

    .batch-file-upload-dialog__label {
        width: 80px;
        text-align: right;
        margin-right: 20px;
    }

    .batch-file-upload-dialog .upload-file-list__item {
        width: 180px;
        height: 180px;
    }

    .batch-file-upload-dialog .upload-file-list__item-wrapper {
        width: 600px;
        padding: 10px;
        margin-bottom: 20px;
        border: 1px solid #ccc;
        position: relative;
    }

    .batch-file-upload-dialog .upload-file-list__item {
        position: relative;
    }

    .batch-file-upload-dialog .upload-file-list__item img {
        max-width: 100%;
        max-height: 100%;
    }

    .batch-file-upload-dialog .upload-file-list__error {
        position: absolute;
        background: #000;
        opacity: 0.7;
        color: #fff;
        width: 100%;
        font-size: 12px;
        padding: 5px;
        display: block;
        box-sizing: border-box;
    }

    .batch-file-upload-dialog .upload-file-list__remove {
        position: absolute;
        color: red;
        cursor: pointer;
        top: 10px;
        right: 10px;
    }
    .project-type-selector .el-tag {
        margin: 10px;
        cursor: pointer;
    }
</style>